package com.clown.smsbase.Service.impl;

import com.clown.smsbase.Dao.GenericTreeDao;
import com.clown.smsbase.Domain.BaseTreeEntity;
import com.clown.smsbase.Service.GenericTreeManager;

import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Transactional
public class GenericTreeManagerImpl<T extends BaseTreeEntity<T, PK>, PK extends Serializable>
        extends GenericManagerImpl<T, PK> implements GenericTreeManager<T, PK> {

    protected GenericTreeDao<T, PK> treeDao;

    @Override
    public List<T> getAncestors(PK id) {
        List<T> ancestors = new ArrayList<T>();
        T entity = this.treeDao.findById(id).get();
        T parent = entity.getParent();
        while (parent != null) { // 追述祖先
            ancestors.add(parent);
            entity = parent;
            parent = entity.getParent();
        }
        return ancestors;
    }

    @Override
    public List<T> getChildren(PK id) {
        T entity = this.treeDao.findById(id).get();
        return entity.getChildren();
    }

    @Override
    public List<T> getDescendants(PK id) {
        List<T> descendants = new ArrayList<T>();
        List<T> children = this.getChildren(id);
        if (children != null && children.size() > 0) { // 追加子孙
            descendants.addAll(children);
            for (T t : children) {
                List<T> descendants2 = this.getDescendants(t.getId());
                descendants.addAll(descendants2);
            }
        }
        // if (children != null && children.size() > 0) {
        // descendants.addAll(children);
        // for (T t : children) {
        // @SuppressWarnings("unchecked")
        // List<T> descendants2 = this.getDescendants((PK) t.getId());
        // descendants.addAll(descendants2);
        // }
        // }
        return descendants;
    }

    @Override
    public List<T> getRoot() {
        return this.treeDao.getRoot();
    }
}
